package cn.song.config;

import cn.song.config.convert.factory.IntegerCodeToEnumConverterFactory;
import cn.song.config.convert.factory.StringCodeToEnumConverterFactory;
import cn.song.util.FilePath;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.core.io.Resource;
import org.springframework.web.servlet.resource.PathResourceResolver;
import org.springframework.web.servlet.resource.ResourceResolverChain;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;

/**
 * MVC通用配置
 *
 * @author SongRenShuo
 * @date 2025/01/05
 */
@Slf4j
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @PostConstruct
    public void init() {
        File directory = new File(FilePath.ABSOLUTE_PATH);
        if (!directory.exists()) {
            boolean created = directory.mkdirs();
            log.info("创建目录 {} {}", FilePath.ABSOLUTE_PATH, created ? "成功" : "失败");
        }
        log.info("静态资源目录检查 - 绝对路径: {}, 相对路径: {}", FilePath.ABSOLUTE_PATH, FilePath.RELATIVE_PATH);
    }

    /**
     * 枚举类的转换器工厂 addConverterFactory
     */
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverterFactory(new IntegerCodeToEnumConverterFactory());
        registry.addConverterFactory(new StringCodeToEnumConverterFactory());
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 添加文件系统路径检查
        File directory = new File("C:/SpringbootExcelDemo/down");
        log.info("检查目录是否存在: {} - {}", directory.getAbsolutePath(), directory.exists());
        if (directory.exists()) {
            File[] files = directory.listFiles();
            if (files != null) {
                for (File file : files) {
                    log.info("目录下的文件: {}", file.getName());
                }
            }
        }

        // 配置默认静态资源映射（classpath:/static/）
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/static/")
                .setCachePeriod(0);

        // 配置自定义静态资源映射
        String resourcePattern = "/SpringbootExcelDemoFile/**";
        String resourceLocation = "file:C:/SpringbootExcelDemo/";

        registry.addResourceHandler(resourcePattern)
                .addResourceLocations(resourceLocation)
                .setCachePeriod(0)
                .resourceChain(true)
                .addResolver(new PathResourceResolver() {
                    @Override
                    protected Resource resolveResourceInternal(HttpServletRequest request, String requestPath,
                                                            List<? extends Resource> locations, ResourceResolverChain chain) {
                        log.info("正在解析资源 - 请求路径: {}", requestPath);
                        Resource resource = super.resolveResourceInternal(request, requestPath, locations, chain);
                        log.info("资源解析结果: {}", resource != null ? "找到资源" : "未找到资源");
                        return resource;
                    }
                });

        log.info("静态资源映射配置完成 - 默认映射: classpath:/static/, 自定义映射: pattern: {}, location: {}", resourcePattern, resourceLocation);
    }

    // 输出每一个拦截打到的访问路径
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LogInterceptor()).addPathPatterns("/**");
    }

    public static class LogInterceptor implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
            String url = request.getRequestURI();
            String method = request.getMethod();
            String ip = request.getRemoteAddr();
            String queryString = request.getQueryString();

            log.info("请求拦截 - URL: {}, Method: {}, IP: {}, Query: {}", url, method, ip, queryString);
            log.info("请求路径信息 - 完整URL: {}, URI: {}, ContextPath: {}, ServletPath: {}",
                    request.getRequestURL(),
                    request.getRequestURI(),
                    request.getContextPath(),
                    request.getServletPath());

            return true;
        }
    }
}
